package com.light.gulimall.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.light.common.constants.Result;
import com.light.common.utils.R;
import com.light.gulimall.auth.dto.LoginDTO;
import com.light.gulimall.auth.feign.MemberRemoteFeignClient;
import com.light.gulimall.auth.feign.ThridPartyRemoteFeignClient;
import com.light.gulimall.auth.service.LoginService;
import com.light.gulimall.auth.vo.UserRegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private ThridPartyRemoteFeignClient feignClient;

    @Autowired
    private MemberRemoteFeignClient memberRemoteFeignClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final String cacheKey="message:";

    /**
     * 发送验证码
     *
     * @param phone 手机号
     * @param code  验证码
     * @return 发送结果
     */
    @Override
    public R sendMessageCode(String phone, String code) {
        //缓存key:"message:"拼接上各自的手机号
        String result = stringRedisTemplate.opsForValue().get(cacheKey + phone);
        if (StringUtils.isNotBlank(result)) {
            return R.error("请勿重复发送！");
        }
        //发送短信
        R r = feignClient.sendMessageCode(phone, code);
        //发送成功才需要向缓存中存放手机号和对应的验证码
        if (r.get("msg").equals("success")) {
            stringRedisTemplate.opsForValue().set(cacheKey+phone, JSON.toJSONString(code),60, TimeUnit.SECONDS);
        }
        //注意，后续手机号验证码校验完成后也需要删除缓存中对应的
        return r;
    }

    /**
     * 校验验证码信息
     *
     * @param vo 前端传递
     * @return 校验结果
     */
    @Override
    public R checkCode(UserRegisterVo vo) {
        String phone = vo.getPhone();
        String code = vo.getCode();
        String result = stringRedisTemplate.opsForValue().get(cacheKey + phone);
        String codeRedis = JSON.parseObject(result, String.class);
        if (StringUtils.isBlank(codeRedis)) {
            return R.error(Result.ERROR,"验证码不存在!");
        }
        if (!code.equals(codeRedis)) {
            return R.error(Result.ERROR,"验证码错误!");
        }else {
            //删除缓存中的验证码，返回提示
            stringRedisTemplate.delete(cacheKey + phone);
            return R.ok();
        }
    }

    /**
     * 用户注册,远程调用gulimall-member服务
     *
     * @param vo 注册信息
     */
    @Override
    public R register(UserRegisterVo vo) {
        return memberRemoteFeignClient.regist(vo);
    }

    /**
     * 用户登录,远程调用gulimall-member服务
     *
     * @param dto 登录信息
     * @return 返回结果
     */
    @Override
    public R login(LoginDTO dto) {
        return memberRemoteFeignClient.login(dto);
    }
}
